﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Device.Location;
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using Microsoft.Phone.Tasks;
using System.Windows.Controls;

namespace ThessalonikiGuide
{
    public partial class Page1 : PhoneApplicationPage
    {
        public static bool Back;
        private ItemFlyInAndOutAnimations _flyOutAnimation = null;
        private readonly GeoCoordinateWatcher _watcher = new GeoCoordinateWatcher();
        private List<XElement> _items;
        private string _name;
        public Page1()
        {
            InitializeComponent();
            _watcher.Start();
            Dispatcher.BeginInvoke(() => {
                if (_flyOutAnimation != null)
                {
                    _flyOutAnimation.ItemFlyIn();
                }});
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_flyOutAnimation != null)
            {
                _flyOutAnimation.ItemFlyIn();
            }
            _name = NavigationContext.QueryString["cat"];
            Init();
        }
        private void Init()
        {
            PageTitle.Text = _name;
            var doc = XDocument.Load("poi_thessalonikis.xml");
            _items =
                doc.Descendants("Placemark").Where(
                    y => Simple(y, "newcat")
                     == _name ||
                    Simple(y, "newsubcat") == _name).ToList();
            Update();
        }
        public static string Simple(XElement el, string name)
        {
            return SimpleRaw(el, name) == null ? null : SimpleRaw(el,name).Value;
        }
        public static XElement SimpleRaw(XElement el, string name)
        {
            try
            {
                return el.Element("ExtendedData").Element("SchemaData").Elements("SimpleData").Single(y => y.Attribute("name").Value == name);
            }
            catch (InvalidOperationException) { return null; }
        }
        public class Place : INotifyPropertyChanged
        {
            private string _phone = "";
            private string _text = "";
            private string _address = "";
            private string _coordinates = "";
            public string phone
            {
                get { return _phone; }
                set { _phone = value; NotifyPropertyChanged("phone"); }
            }
            public string coordinates
            {
                get { return _coordinates; }
                set { _coordinates = value; NotifyPropertyChanged("coordinates"); }
            }
            public string address
            {
                get { return _address; }
                set { _address = value; NotifyPropertyChanged("address"); }
            }
            public string text
            {
                get { return _text; }
                set { _text = value; NotifyPropertyChanged("text"); }
            }
            public event PropertyChangedEventHandler PropertyChanged;

            private void NotifyPropertyChanged(String info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }

        }
        private void Update()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            listBox1.ItemsSource = (from item in _items
                                    let address = SimpleRaw(item, "address")
                                    let phone = SimpleRaw(item, "phone")
                                    let geocoordinates =
                                        item.Element("Point").Element("coordinates").
                                        Value.Split(new char[] { ',' })
                                    select new Place()
                                    {
                                        coordinates = geocoordinates[0] + "," + geocoordinates[1],
                                        text =
                                            Math.Round(
                                            _watcher.Position.Location.GetDistanceTo(
                                            new GeoCoordinate(Convert.ToDouble(geocoordinates[1]),
                                                  Convert.ToDouble(geocoordinates[0]))) / 1000, 2) +
                                            " χμ - " + item.Element("name")
                                            .Value,
                                        address = address != null ? address.Value : "",
                                        phone = phone != null ? phone.Value : ""
                                    }).OrderBy(y => Convert.ToDouble(y.text.Split(new string[]{"χμ"},StringSplitOptions.None)[0])).ToList();
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Back = true;
            base.OnBackKeyPress(e);
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PhoneCallTask task = new PhoneCallTask();
            task.PhoneNumber = ((HyperlinkButton)sender).Content.ToString();
            task.DisplayName = ((TextBlock)((StackPanel)((HyperlinkButton)sender).Parent).Children[0]).Text;
            task.Show();
        }

        private void TextBlock_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ((StackPanel)((StackPanel)((TextBlock)sender).Parent).Children[1]).Visibility = ((StackPanel)((StackPanel)((TextBlock)sender).Parent).Children[1]).Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            ((StackPanel)((StackPanel)((StackPanel)((TextBlock)sender).Parent).Children[1]).Children[1]).Visibility = ((HyperlinkButton)((StackPanel)((StackPanel)((StackPanel)((TextBlock)sender).Parent).Children[1]).Children[1]).Children[1]).Content.ToString() == "0" ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _flyOutAnimation = new ItemFlyInAndOutAnimations();
            _flyOutAnimation.ItemFlyOut((Button)sender, () =>
            {
                NavigationService.Navigate(new Uri("/GPS.xaml?coordinates=" + ((TextBlock)((StackPanel)((StackPanel)((Button)sender).Parent).Parent).Children[2]).Text + "&name=" + ((TextBlock)((StackPanel)((StackPanel)((Button)sender).Parent).Parent).Children[0]).Text.Split(new string[1] { "χμ - " }, StringSplitOptions.None)[1], UriKind.Relative));
            });   
        }
    }
}